/**
 * Created by tedi on 2018/3/27.
 */
odoo.define('lift_base.ceo_index', function (require) {
    "use strict";
    
    var ajax = require('web.ajax');
    var core = require('web.core');
    var Widget = require('web.Widget');
    var Model = require('web.Model');
    var session = require('web.session');
    var framework = require('web.framework');
    var chartjs = require("lift_base.chartjs_widget");
    var ChartJSBarWidget = chartjs.ChartJSBarWidget;
    var TyibsChartPie = chartjs.TyibsChartPie;
    var TyibsChartLine = chartjs.TyibsChartLine;

    var common_widget = require('lift_base.common_widget');

    var lift_model = new Model("tyibs.base.lift");
    lift_model._context = {'search_from':'lift_distribution'};

    //首页上显示的区域图列表项
    var AreaMapListItemWidget = Widget.extend({
        template: "tyibs_chart_map_ul_item_template",
        events:{
          'click a':"show_lift_list_view",
        },
        init: function(parent, name, count , area_id){
            this._super(parent);
            this.name = name;
            this.count = count;
            this.area_id = area_id;
        },
        show_lift_list_view:function(){
            var self = this;
            self.do_action({
                name: self.name,
                type: 'ir.actions.act_window',
                res_model: "tyibs.base.lift",
                domain: [['area_id','=', self.area_id]],
                views: [[false, 'list'],[false, 'form']],
                target: 'current',
                context: {},
            });
            return false;
        }
    });

    //首页上显示的区域图
    var AreaMapWidget = Widget.extend({
        template:"tyibs_chart_map_template",
        init:function(parent, ids, labels, row_data){
            this._super(parent);
            this.ids = ids;
            this.labels = labels;
            this.row_data = row_data;
            this.data_set = labels.map(function(label, index){ return {'name':label, 'value':row_data[index], 'id': ids[index]}});
        },
        start:function(){
            var self = this;
            //echarts比较傻逼，这样取不到元素，会报错
            //var map_container = self.$("div.tyibs-chart-map");
            var map_container = self.$el[0].childNodes[3].childNodes[1].childNodes[1];
            var group_container = self.$("ul.list-group");
            $.get("/lift_base/static/src/geojson/320200.json",function(data){
                self.generate_map(map_container, data);
            });

            self.labels.forEach(function(label, index){
                var list_item = new AreaMapListItemWidget(self, label, self.row_data[index], self.ids[index]);
                list_item.appendTo(group_container);
            });
        },
        generate_map:function(map_container, map_data){
            var self = this;
            var map_chart = echarts.init(map_container);
            map_chart.hideLoading();
            echarts.registerMap('zmd', map_data);
            map_chart.setOption({
                tooltip: {
                    trigger: 'item',
                    formatter: '{b}<br/>{c}部'
                },
                toolbox: {
                    show: false,
                    orient: 'vertical',
                    left: 'right',
                    top: 'center',
                    feature: {
                        dataView: {readOnly: false},
                        restore: {},
                        saveAsImage: {}
                    }
                },
                visualMap: {
					show:false,
                    min: 100,
                    max: 50000,
                    text:['High','Low'],
                    realtime: false,
                    calculable: true,
                    inRange: {
                        color: ['#00c0ef']
                    }
                },
                series: [
                    {
                        name: '各县区电梯分部情况',
                        type: 'map',
                        mapType: 'zmd', // 自定义扩展图表类型
                        itemStyle:{
                            normal:{label:{show:true}},
                            emphasis:{label:{show:true}}
                        },
                        data:self.data_set,
                    }
                ]
            });
            map_chart.on('click',function(params){
                if(params.data == undefined ){
                    return false;
                }
                self.show_lift_list_view(params.data.name, params.data.id);
                return false;
            });
        },
        show_lift_list_view:function(name, area_id){
            var self = this;
            self.do_action({
                name: name,
                type: 'ir.actions.act_window',
                res_model: "tyibs.base.lift",
                domain: [['area_id','=', area_id]],
                views: [[false, 'list'],[false, 'form']],
                target: 'current',
                context: {},
            });
        }
    });

    var MessageBox = Widget.extend({
        template: "count_message_box",
        events:{
            'click a.more': 'show_list_view',
        },
        init: function(parent, model_name, domain, action, title, icon_class, bg_class){
            this._super(parent);
            this.model = new Model(model_name);
            this.model._context = {'search_from':'lift_distribution'};
            this.action = action;
            this.title = title;
            this.domain = domain;
            this.count = 0;
            this.icon_class = icon_class;
            this.bg_class = bg_class;
        },
        start: function(){
            this.get_count_data();
        },
        get_count_data:function(){
            var self = this;
            var query = this.model.query(self.domain);
            if(self.domain!=undefined && self.domain!=null && this.domain.length>0){
                query = query.filter(self.domain);
            }
            query.count().then(function(result){
                self.$("h3.message-count").text(result);
            });
        },
        show_list_view:function(){
            this.do_action({
                name: this.title,
                type: 'ir.actions.act_window',
                res_model: this.model.name,
                domain: this.domain==null ||this.domain==undefined || this.domain.length<1 ? []:this.domain,
                views: [[false, 'list'],[false, 'form']],
                target: 'current',
                context: {},
            });
            return false;
        }
    });

    var QsIndex = Widget.extend({
        template:"qs_index",
        init:function(parent){
            this._super(parent);
        },
        start:function(){
            // 4个电梯数量柱状图
            this.get_data_groupby_area();
            // 预警监测
            this.get_count_data();
            // 维保救援检验-饼图
            this.generate_pie_chart();
            // 救援按时间统计曲线图
            this.generate_line_chart();
        },
        get_count_data:function(){
            new MessageBox(this,"tyibs.base.lift",[],"","电梯数量","fa-subway","bg-aqua").appendTo(this.$("div.tyibs-message-box-container"));
            new MessageBox(this,"tyibs.base.maintenance.company",[['is_salvager_unit','=',true]],"","救援单位","fa-ambulance","bg-aqua").appendTo(this.$("div.tyibs-message-box-container"));
            var current_date = moment().format('YYYY-MM-DD');
            // 2018-09-04超期未检去除整改期间的电梯
            new MessageBox(this,"tyibs.base.lift",[['next_check_date','<',current_date],['lift_status','=','using'],['checkout_result','!=','corrective']],"","超期未检","fa-subway","bg-red").appendTo(this.$("div.tyibs-message-box-container"));
            new MessageBox(this,"tyibs.base.maintenance.company.employee.certificate",[['has_over_time','=',true]],"","维保人员证书到期","fa-credit-card","bg-red").appendTo(this.$("div.tyibs-message-box-container"));
            new MessageBox(this,"tyibs.base.maintenance.company",[['next_filing_date','<',current_date]],"","维保单位备案到期","fa-wrench","bg-red").appendTo(this.$("div.tyibs-message-box-container"));
        },
        get_data_groupby_area:function(){
            var self = this;
            self.get_area_group_data(function(ids, labels,data){
                new ChartJSBarWidget(self, "区/县电梯数量统计", data, labels, "#00a65a", "active").appendTo(self.$("div.carousel-inner"));
                new AreaMapWidget(self, ids, labels, data).appendTo(self.$("div.tyibs-map")[0]);
            });

            self.get_group_data("category_id","category_id",function(labels,data){
                new ChartJSBarWidget(self, "电梯分类数量统计", data, labels, "#00c0ef", "").appendTo(self.$("div.carousel-inner"));
            });

            self.get_group_data("place_id","place_id",function(labels,data){
                new ChartJSBarWidget(self, "电梯使用场所数量统计", data, labels, "#dd4b39", "").appendTo(self.$("div.carousel-inner"));
            });

            self.get_group_data("made_date","made_date:year",function(labels,data){
                new ChartJSBarWidget(self, "电梯制造日期数量统计", data, labels, "#ff851b", "").appendTo(self.$("div.carousel-inner"));
            });
        },
        generate_pie_chart:function(){
            var self = this;
            var numByName=function(arr,name){
                var num = 0;
                arr.forEach(function(item){item.attributes.value==name&&(num+=item.attributes.length)})
                return num
            }
            
            // 按组查询:base里面查维保工单好像不太合适.......
            // alive 可以防止widget在函数返回结果之前就被销毁
            // 电梯维保饼图
            self.alive(new Model("tyibs.main.work.order").query(['over_due_state']).group_by(['over_due_state']))
            .then(function(result){
                var maintenance_labels=["超期维保","超期未维保","正常"];
                var maintenance_data = [];
                maintenance_data.push(numByName(result,'over_due_has_main'));
                maintenance_data.push(numByName(result,'over_due_not_main'));
                maintenance_data.push(numByName(result,'normal'));
                var maintenance_bg_colors = ["#2A7AA0","#F3FFBD","#70C0B3","#B3DBC0"];
                new TyibsChartPie(self, 'pie', "电梯维保", maintenance_labels, maintenance_data, maintenance_bg_colors).appendTo(self.$("div.chart-area"));
            });

            //救援到达
            self.alive(new Model("tyibs.lift.er.arrive.timespan.report").query(['arrive_timespan','save_count']).all())
            .then(function(result){
                var numByKey=function(arr,val){
                    var num = 0;
                    arr.forEach(function(item){item['arrive_timespan']==val&&(num+=item['save_count'])})
                    return num
                }
                var save_labels=["0-10min","10-20min","20-30min","超过30min"];
                var save_data = [];
                save_data.push(numByKey(result,1)+numByKey(result,2));
                save_data.push(numByKey(result,3)+numByKey(result,4));
                save_data.push(numByKey(result,5)+numByKey(result,6));
                save_data.push(numByKey(result,7));
                var save_bg_colors = ["#2A7AA0","#F3FFBD","#70C0B3","#B3DBC0"];
                new TyibsChartPie(self, 'pie', "救援到达", save_labels, save_data, save_bg_colors).appendTo(self.$("div.chart-area"))
            });

            // 救援响应饼图:这里有个坑：后台出来0，这里会自动转换成false
            // 后台修改：从0~6改为1~7
            self.alive(new Model("tyibs.lift.er.save.finished.timespan.report").query(['save_finished_timespan','save_count']).all())
            .then(function(result){
                var numByKey=function(arr,val){
                    var num = 0;
                    arr.forEach(function(item){item['save_finished_timespan']==val&&(num+=item['save_count'])})
                    return num
                }
                var save_labels=["0-10min","10-20min","20-30min","超过30min"];
                var save_data = [];
                save_data.push(numByKey(result,1)+numByKey(result,2));
                save_data.push(numByKey(result,3)+numByKey(result,4));
                save_data.push(numByKey(result,5)+numByKey(result,6));
                save_data.push(numByKey(result,7));
                var save_bg_colors = ["#2A7AA0","#F3FFBD","#70C0B3","#B3DBC0"];
                new TyibsChartPie(self, 'pie', "救援响应", save_labels, save_data, save_bg_colors).appendTo(self.$("div.chart-area"))
            });
        },
        get_area_group_data:function(call_back){
            //比较特殊,需要获取到组的ID
            this.alive(lift_model.query(['area_id']).group_by(['area_id']))
            .then(function (groups) {
                var labels = [];
                var data = [];
                var ids = [];
                groups.forEach(function(item){
                    ids.push(item.attributes.value[0]);
                    labels.push(item.attributes.value[1]);
                    data.push(item.attributes.length);
                });
                call_back(ids, labels, data);
            });
        },
        get_group_data: function(query_field, group_field, call_back){
            this.alive(lift_model.query([query_field]).group_by([group_field]))
            .then(function (groups) {
                var labels = [];
                var data = [];
                groups.forEach(function(item){
                    //只有一条记录时，返回的value是普通的string
                    if(item.attributes.value == false){
                        labels.push("未定义");
                    }
                    else if( typeof(item.attributes.value) == "string"){
                        labels.push(item.attributes.value);
                    }else{
                        labels.push(item.attributes.value[1]);
                    }
                    data.push(item.attributes.length);
                });
                call_back(labels, data);
            });
        },
        generate_line_chart:function(){
            var self = this;

            self.alive( new Model("tyibs.er.work.order.save").query(['service_time']).group_by(['service_time']) )
            .then(function(result){
                var l_labels = [];
                var l_data = [];
                result.forEach(function(item){
                    l_labels.push(item.attributes.value);
                    l_data.push(item.attributes.length);
                })
                new TyibsChartLine(self, "line","电梯救援数量", l_labels.slice(-6),l_data.slice(-6), "#2A7AA0").appendTo(self.$("div.chart-line-area"));
            })
        }
    });

    var BaiduMapLiftDistributionWidget = Widget.extend({
        template: "baidu_map_lift_distribution",
        init:function(parent){
            this._super(parent);
            this.model = lift_model;
            this.use_company_model = new Model("tyibs.base.lift.use.company");
            this.point_collection_options = {
                size: BMAP_POINT_SIZE_BIG,
                shape: BMAP_POINT_SHAPE_WATERDROP,
                color: '#f54336',
            };
            this.full_screen_flag = false;
            this.hide_menu_flag = false;

            this.area_list_flag = false;
            this.use_company_search_flag = 0; //0未加载，1加载后显示，2加载后隐藏
        },
        start: function () {
            $(".o_sub_menu").show();
            $(".navbar.navbar-inverse").show();

            var map = new BMap.Map(this.$el[0], {
                minZoom : 10,
            });
            map.enableScrollWheelZoom(true);
            this.map = map;
            this.marker_clusterer = new BMapLib.MarkerClusterer(map);

            /*
            这里的charts报表会引起offWidth错误
            //charts报表
            var charts_widget = new BaiduMapLiftDistributionChartsWidget(this);
            this.charts_widget = charts_widget;
            charts_widget.appendTo(this.$el);
            this.get_data_groupby_area();
            */

            var self = this;
            // 先查询默认城市
            common_widget.get_default_city(function (city) {
                self.city = city;
                self.init_load();
            });
        },
        init_load: function () {
            //按钮区
            var btn_block_widget = new BaiduMapLiftDistributionBtnBlockWidget(this);
            btn_block_widget.on("show_or_hide_menu", this, this.show_or_hide_menu);
            btn_block_widget.on("all_lift", this, this.all_lift);
            btn_block_widget.on("using_lift", this, this.using_lift);
            btn_block_widget.on("statistics_lift", this, this.statistics_lift);
            // btn_block_widget.on("show_or_hide_charts", this, this.show_or_hide_charts);
            btn_block_widget.on("show_or_hide_search", this, this.show_or_hide_search);
            btn_block_widget.on("full_screen", this, this.full_screen);
            btn_block_widget.appendTo(this.$el);
            this.btn_block_widget = btn_block_widget;

            //搜索区
            var search_block = new BaiduMapLiftDistributionWidgetSearchBlock(this);
            this.search_block = search_block;
            search_block.on("search_lift", this, this.search_lift);
            search_block.on("search", this, this.search);
            search_block.appendTo(btn_block_widget.$el);
            search_block.$el.hide();

            //放区域电梯总数的列表
            var area_list_widget = new BaiduMapLiftDistributionAreaListWidget(this, "tyibs.base.lift", "area_id");
            this.area_list_widget = area_list_widget;
            area_list_widget.on("search_lift_by_area_id", this, this.search_lift_count_group_by_use_company);
            area_list_widget.appendTo(this.$el);
            area_list_widget.$el.hide();

            this.statistics_lift();
        },
        go_to_lift_list: function (args) {
            this.do_action({
                name: args["title"],
                type: 'ir.actions.act_window',
                res_model: "tyibs.base.lift",
                domain: args["domain"],
                views: [[false, 'list'],[false, 'form']],
                target: 'current',
                context: {},
            });
            return false;
        },
        statistics_lift_data: function (area_id, area_name) {
            //切换统计数据
            var self = this;
            if (self.statistics_data){
                self.statistics_data.$el.remove();
            }
            var statistics_data = new BaiduMapLiftDistributionStatisticsWidget(self,area_id, area_name);
            self.statistics_data = statistics_data;
            statistics_data.on("go_to_lift_list", self, self.go_to_lift_list);
            statistics_data.appendTo(self.btn_block_widget.$el);
        },
        search: function (fields, domain, limit) {
            limit = limit ? limit : 0;
            return this.model.query(fields).filter(domain).limit(limit).all();
        },
        show_baidu_map: function () {
            //初始化使用海量点加载所有电梯
            this.search_point_collection([]);
            this.add_area_boundary();
        },
        clear_all_overlay: function () {
          this.map.clearOverlays();
          this.marker_clusterer.clearMarkers();
        },
        all_lift: function () {
            this.reset_search_block();
            this.clear_all_overlay();
            this.add_area_boundary();
            this.search_point_collection([]);
            this.statistics_lift_data();
        },
        using_lift: function () {
            this.clear_all_overlay();
            this.add_area_boundary();
            this.search_point_collection([['lift_status', '=', 'using']]);
            this.statistics_lift_data();
        },
        statistics_lift: function () {
            this.clear_all_overlay();
            this.add_map_polygon();
            this.add_map_labels();
            this.reset_search_block();
            this.statistics_lift_data();
        },
        show_or_hide_menu: function () {
            $(".navbar.navbar-inverse").toggle();
            $(".o_sub_menu").toggle();
            var $btn = this.$el.find(".show_or_hide_menu");
            if (this.hide_menu_flag){
                $btn.html("隐藏菜单");
            }else{
                $btn.html("显示菜单");
            }
            this.hide_menu_flag = !this.hide_menu_flag;
        },
        full_screen: function () {
            var element = document.getElementById("baidu_map_lift_distribution");
            var $btn = this.$el.find(".full_screen");
            if (this.full_screen_flag){
                if (document.webkitCancelFullScreen){
                    document.webkitCancelFullScreen();
                }else if(document.mozCancelFullScreen){
                    document.mozCancelFullScreen();
                }else if(document.msExitFullscreen){
                    document.msExitFullscreen();
                }
                $btn.html("全屏显示");
            }else{
                if (element.webkitRequestFullScreen){
                    element.webkitRequestFullScreen();
                }else if(element.mozRequestFullScreen){
                    element.mozRequestFullScreen();
                }else if(element.msRequestFullscreen){
                    element.msRequestFullscreen();
                }
                $btn.html("取消全屏");
            }
            this.full_screen_flag = !this.full_screen_flag;
            $(".show_or_hide_menu").toggle();
        },
        /*
        这里的charts报表会引起offWidth错误
        show_or_hide_charts: function () {
            this.charts_widget.$el.toggle();
            var $btn = this.$el.find(".show_or_hide_charts");
            if ($btn.hasClass("charts_display_none")){
                $btn.html("隐藏报表");
                $btn.removeClass("charts_display_none");
            }else{
                $btn.html("显示报表");
                $btn.addClass("charts_display_none");
            }
        },
        */
        show_or_hide_search: function () {
            var self = this;
            self.search_block.$el.toggle();
            console.log(self.use_company_search_flag);
            var $btn = self.$el.find(".show_or_hide_search");
            if ($btn.hasClass("search_display_none")){
                if (self.use_company_search_flag == 1){
                    //在区县视角
                    self.use_company_search_block_widget.$el.show();
                }else {
                    // 非区县视角
                    self.area_list_widget.$el.show();
                }
                $btn.html("隐藏搜索");
                $btn.removeClass("search_display_none");
            }else{
                if (self.use_company_search_flag == 1){
                    //在区县视角
                    self.use_company_search_block_widget.$el.hide();
                }else {
                    // 非区县视角
                    self.area_list_widget.$el.hide();
                }
                $btn.html("显示搜索");
                $btn.addClass("search_display_none");
            }
        },
        reset_search_block: function () {
            if (this.search_block != undefined){
                this.search_block.$el.find("input").val("");
            }

            if (this.use_company_search_block_widget != undefined){
                this.use_company_search_block_widget.$el.remove();
            }

            if (this.lift_search_block_widget != undefined){
                this.lift_search_block_widget.$el.remove();
            }

            this.use_company_search_flag = 0;
            // if (this.btn_block_widget != undefined){
            //     this.btn_block_widget.$el.find(".show_or_hide_search").click();
            // }
        },
        search_lift: function (domain, center, zoom) {
            this.clear_all_overlay();
            this.search_point_collection(domain, center, zoom)
        },
        search_point_collection: function (domain, center, zoom) {
            /*
            搜索海量点
             */
            var self = this;
            center = center != undefined ? center : self.city.name;
            zoom = zoom != undefined ? zoom : 10;
            self.search(["ln", "la"], domain).then(function (result) {
                var points = [];
                for (var i = 0; i < result.length; i ++) {
                    var point = new BMap.Point(result[i].ln, result[i].la);
                    point.index = result[i].id;
                    points.push(point)
                };
                self.add_point_collection(points, center, zoom);
            });
        },
        add_point_collection: function (points, center, zoom) {
            /*
            添加海量点
             */
            var self = this;
            var pointCollection = new BMap.PointCollection(points, self.point_collection_options); // 初始化PointCollection
            pointCollection.addEventListener('click', function (e) {
                var marker_id = e.point.index;
                var point = new BMap.Point(e.point.lng, e.point.lat);
                self.search(["register_code", "use_company_id", "use_address", "lift_status", "code", "next_check_date",
                    "maintenance_company_id", "last_maintenance_date"], [['id', '=', marker_id]]).then(function (results) {
                    self.bind_open_info_window(results[0], point);
                });
            });
            self.map.centerAndZoom(center, zoom);
            self.map.addOverlay(pointCollection); // 添加Overlay
        },
        add_marker: function (point, marker_text, name) {
            var self = this;
            // var icon = new BMap.Icon("/lift_base/static/src/img/strawberry.png",new BMap.Size(60,60));
            var icon = new BMap.Icon("http://api.map.baidu.com/library/TextIconOverlay/1.2/src/images/m0.png",new BMap.Size(100,100));
            var marker = new BMap.Marker(point, {icon: icon});
            var label = new BMap.Label(marker_text, {offset: new BMap.Size(20, 20)});
            label.setStyle({
                fontSize: '5px',
                color: "white",
                background:'none',
                border:'none',
            });
            marker.setTitle(name);
            marker.setLabel(label);

            self.map.addOverlay(marker);
            marker.addEventListener("click", function(e){
                var marker_id = point.index;
                self.use_company_model.query(["id", "ln", "la", "name", "lift_count"]).filter([['id', '=', marker_id]]).limit(1).all().then(function (result) {
                    result = result[0];
                    self.search_lift_by_use_company_id(result.id, result.ln, result.la, result.name, result.lift_count);
                });
            });
        },
        bind_open_info_window: function (result, point) {
            /*
            绑定点击弹窗
             */
            var self = this;
            var use_company = result.use_company_id[1];
            var maintenance_company = result.maintenance_company_id[1];
            new Model("tyibs.er.work.order.save").query("save_finished_time").filter([['lift_id', '=', result.id]]).order_by("-save_finished_time").first().then(function (res) {
                var save_finished_time = "未知";
                if(res){
                    save_finished_time = self.format_unknow_data(res.save_finished_time);
                }
                new Model("tyibs.er.work.order.compliant").query("service_time").filter([['lift_id', '=', result.id]]).order_by("-service_time").first().then(function (re) {
                    var service_time = "未知";
                    if (re){
                        service_time = self.format_unknow_data(re.service_time);
                    }
                    var lift_info_window = new BaiduMapLiftDistributionLiftInfoWindow(self,
                        result.id,
                        self.format_unknow_data(result.use_address),
                        self.format_unknow_data(result.code),
                        self.format_lift_status(result.lift_status),
                        self.format_unknow_data(result.registr_code),
                        self.format_unknow_data(result.next_check_date),
                        self.format_unknow_data(use_company),
                        self.format_unknow_data(maintenance_company),
                        self.format_unknow_data(result.last_maintenance_date),
                        save_finished_time,
                        service_time
                    );
                    lift_info_window.appendTo(self.$el);
                    var infoWindow = new BMap.InfoWindow(lift_info_window.$el[0]);  // 创建信息窗口对象
                    self.map.openInfoWindow(infoWindow,point); //开启信息窗口
                });
            });


        },
        format_unknow_data: function (org) {
            //格式化未知数据
            return org ? org : "未知";
        },
        format_lift_status: function (lift_status) {
            /*
            转换电梯状态
             */
            switch (lift_status){
                case "using":
                    return "在用";
                case "unused":
                    return "停用";
                case "cancel":
                    return "注销";
                default:
                    return "未知";
            }
        },
       
        search_lift_by_area_id: function (domain, name, id) {
            //点击区/县时查询区/县下的电梯，并定位到这个区
            var self = this;
            self.clear_all_overlay();
            this.search_point_collection(domain, name, 11);
            self.add_single_map_polygon(name, undefined, undefined, 5);
        },
        search_lift_count_group_by_use_company: function (domain, name, id) {
            //视角切换至某个区/县，查出某个区/县下所有使用单位的电梯数量，然后逐个添加marker
            var self = this;


            self.clear_all_overlay();
            //隐藏区/县列表
            self.area_list_widget.$el.hide();
            self.area_list_flag = false;
            //给domain元素赋值
            console.log("视角切换至行政区：" + name);
            //展示搜索使用单位的widget
            self.use_company_model.query(["id"]).filter([['area_id', '=', id]]).count().then(function (lift_count) {
                var use_company_search_block_widget = new BaiduMapLiftDistributionUseCompanySearchBlockWidget(self, id, name, lift_count);
                self.use_company_search_block_widget = use_company_search_block_widget;
                use_company_search_block_widget.on("search_lift_by_use_company_id", self, self.search_lift_by_use_company_id);
                use_company_search_block_widget.appendTo(self.$el);
                self.use_company_search_flag = 1;

                self.statistics_lift_data(id, name);
            });

            self.add_single_map_polygon(name, id, undefined, undefined, 5);
            // use_company_model.query(["lift_count", "ln", "la", "name"]).filter(domain).all().then(function (results) {
            //     results.forEach(function (item) {
            //         var point = new BMap.Point(item.ln, item.la);
            //         point.index = item.id;
            //         self.add_marker(point, item.lift_count, item.name);
            //     })
            // });
            self.use_company_model.query(["lift_count", "ln", "la", "name"]).filter(domain).all().then(function (results) {
                self.add_marker_clusterer(results);
            });

            self.map.centerAndZoom(name == "开发区" ? "驿城区" : name, 11);
        },
        add_marker_clusterer: function (position_list) {
            // 点聚合,传入坐标集合
            var self = this;
            var markers = [];
            position_list.forEach(function (item) {
                var point = new BMap.Point(item.ln, item.la);
                point.index = item.id;

                var marker = new BMap.Marker(point);
                marker.setTitle(item.name + "(电梯数量:" + item.lift_count + ")");
                self.map.addOverlay(marker);
                marker.addEventListener("click", function(e){
                    self.search_lift_by_use_company_id(item.id, item.ln, item.la, item.name, item.lift_count);
                });
                markers.push(marker);
            });
            self.marker_clusterer.addMarkers(markers);
        },
        search_lift_by_use_company_id: function (use_company_id,ln,la, name, lift_count) {
            var self = this;
            //视角切换至使用单位
            console.log("视角切换至使用单位：" + name);
            self.clear_all_overlay();
            self.use_company_search_block_widget.$el.hide();
            self.use_company_search_block_widget.$el.remove();
            self.use_company_model.query(["area_id"]).filter([['id', '=', use_company_id]]).limit(1).all().then(function(result){
                var lift_search_block_widget = new BaiduMapLiftDistributionLiftSearchBlockWidget(self, use_company_id, name, lift_count, result[0].area_id[0], result[0].area_id[1]);
                self.lift_search_block_widget = lift_search_block_widget;
                lift_search_block_widget.on("orientate_one_lift", self, self.add_point_collection);
                lift_search_block_widget.on("search_lift_count_group_by_use_company", self, self.search_lift_count_group_by_use_company);
                lift_search_block_widget.on("search_lift", self, self.search_point_collection);
                lift_search_block_widget.appendTo(self.$el);
                self.search_point_collection([['use_company_id', '=', use_company_id*1]], new BMap.Point(ln, la), 15);
            });
        },
        get_areas: function () {
            //获取所有区
            var area_model = new Model("tyibs.base.province.city.area");
            return area_model.query(['name', 'ln', 'la', 'color']).filter([['city_id', '=', this.city.id]]).all();
        },
        add_area_boundary: function () {
            //添加各区/县边界线
            var self = this;
            self.get_areas().then(function (results) {
                results.forEach(function (item) {
                    if (item.name != "开发区"){
                        self.add_single_map_polygon(item.name, item.id, "", "", 3 , "");
                    }
                });
            });
        },
        add_map_polygon: function () {
            /*
            添加地图行政区域覆盖物(市局角度)
             */
            var self = this;
            self.map.centerAndZoom(self.city.name, 10);
            self.get_areas().then(function (results) {
                results.forEach(function (item) {
                    if (item.name != "开发区"){
                        self.add_single_map_polygon(self.city.name + item.name, item.id, item.color, item.color, 1 , "city");
                    }
                });
            });
        },
        add_single_map_polygon: function (name, id, fillColor, strokeColor, strokeWeight, angle_of_view) {
            /*
            生成单个的行政图层
            angle_of_view: 视角，city or area
             */
            var self = this;
            var bdary = new BMap.Boundary();
            // var instead_name = name == "开发区" ? "驿城区" : name;
            bdary.get(name, function(rs) {       //获取行政区域
                var count = rs.boundaries.length; //行政区域的点有多少个
                if (count === 0) {
                    return;
                }
                fillColor = fillColor != undefined ? fillColor : '';
                // strokeColor = strokeColor != undefined && strokeColor != "" ? strokeColor : 'rgb(178, 164, 113)';
                strokeColor = strokeColor != undefined && strokeColor != "" ? strokeColor : 'red';
                strokeWeight = strokeWeight != undefined ? strokeWeight : 1;
                for (var i = 0; i < count; i++) {
                    var ply = new BMap.Polygon(rs.boundaries[i], {
                        strokeWeight: strokeWeight, strokeColor: strokeColor,
                        fillColor: fillColor, fillOpacity: 0.8, strokeStyle: 'dashed'
                    }); //建立多边形覆盖物

                    //如果是市的视角，添加click事件
                    if(angle_of_view != undefined && angle_of_view == "city"){
                        ply.id = id;
                        ply.name = name;
                        ply.addEventListener("click", function (e) {
                            self.search_lift_count_group_by_use_company([['area_id', '=', e.target.id]], e.target.name, e.target.id);
                        });
                    }

                    self.map.addOverlay(ply);
                }
            })
        },
        add_map_labels: function () {
            //添加
            var self = this;
            self.alive(self.model.query("area_id").group_by("area_id")).then(function (results) {
                var lift_count_datas = {}
                results.forEach(function (item) {
                    lift_count_datas[item.attributes.value[0]] = item.attributes.length
                });
                self.get_areas().then(function (results) {
                    results.forEach(function (item) {
                        var point = new BMap.Point(item.ln, item.la);
                        var lift_count = lift_count_datas[item.id] != undefined ? lift_count_datas[item.id] : 0;
                        var label = new BMap.Label(item.name + ":" + lift_count, {position : point});
                        label.setStyle({
                            fontSize: '30px',
                            color: "white",
                            background:'none',
                            border:'none',
                        });
                        self.map.addOverlay(label);
                    })
                });
            });
        }
    });

    var BaiduMapLiftDistributionWidgetSearchBlock = BaiduMapLiftDistributionWidget.extend({
        template: "baidu_map_lift_distribution_search_block",
        //电梯分布图右侧搜索框
        init: function (parent) {
            this._super(parent);
        },
        events: {
            'click button.o_baidu_map_lift_distribution_search_btn': function () {
                var search_parm = this.$el.find(".o_search_input").val().trim();
                if (search_parm.indexOf("-") != -1){
                    search_parm = search_parm.split("-")[0];
                    this.trigger('search_lift', [['code', '=', search_parm]]);
                }else {
                    this.trigger('search_lift', ['|', ['code', 'ilike', search_parm], '|', ['area_id.name', 'ilike', search_parm], '|',
                        ['use_company_id.name', 'ilike', search_parm], '|',['maintenance_company_id.name', 'ilike', search_parm],
                    ['use_address', 'ilike', search_parm]]);
                }
            },
            'keydown input.o_search_input': function (e) {
                if(e.keyCode == 13){
                    var search_parm = this.$el.find(".o_search_input").val().trim();
                    if (search_parm.indexOf("-") != -1){
                        search_parm = search_parm.split("-")[0];
                        this.trigger('search_lift', [['code', '=', search_parm]])
                    }else {
                        this.trigger('search_lift', ['|', ['code', 'ilike', search_parm], '|', ['area_id.name', 'ilike', search_parm], '|',
                            ['use_company_id.name', 'ilike', search_parm], '|',['maintenance_company_id.name', 'ilike', search_parm],
                        ['use_address', 'ilike', search_parm]]);
                    }
                }
            },
            'change :input.o_search_input_hidden': function () {
                this.trigger("search_lift", [['id', '=', this.$el.find("input.o_search_input_hidden").val().trim()]]);
            }
        },
        start: function () {
            var self = this;
            self.$el.find(".o_search_input" ).autocomplete({
                source: function (request, response) {
                    var vals = [];
                    self.search(["register_code", "use_company_id", "use_address", "code", "maintenance_company_id"],
                        ['|', ['code', 'ilike', request.term], '|', ['area_id.name', 'ilike', request.term], '|',
                            ['use_company_id.name', 'ilike', request.term], '|',['maintenance_company_id.name', 'ilike', request.term],
                        ['use_address', 'ilike', request.term]], 10).then(function (results) {
                        results.forEach(function (item) {
                            var value = item.code + "-" + item.use_company_id[1]+ "-" + item.use_address;
                            vals.push({id: item.id, label: value, value: value});
                        });
                        response(vals);
                        return;
                    });
                },
                select: function( event, ui ) {
                    var $input_hidden = self.$el.find("input.o_search_input_hidden");
                    $input_hidden.val(ui.item.id);
                    $input_hidden.change();
                }
            });
        }
    });


    var BaiduMapLiftDistributionAreaListItemWidget = Widget.extend({
        //左侧区域列表的item
        template: "baidu_map_lift_distribution_area_list_item",
        init: function (parent, name, count, id, group_by) {
            this._super(parent);
            this.name = name;
            this.count = count;
            this.id = id;
            this.group_by = group_by;
        },
        events: {
            "click a": function () {
                this.trigger("search_lift_by_area_id", [[this.group_by, '=', this.id]], this.name, this.id);
            }
        }

    });

    var BaiduMapLiftDistributionAreaListWidget = Widget.extend({
        //左侧区域列表
        template: "baidu_map_lift_distribution_area_list",
        init: function (parent, model_name, group_by) {
            this._super(parent);
            this.model = new Model(model_name);
            this.group_by = group_by;
            this.total_count = 0;
        },
        start: function () {
            var self = this;
            self.get_area_lift_count();
        },
        get_area_lift_count: function () {
            var self = this;
            self.alive(self.model.query(self.group_by).group_by(self.group_by)).then(function (results) {
                results.forEach(function (item) {
                    var area_list_item_widget = new BaiduMapLiftDistributionAreaListItemWidget(self,
                        item.attributes.value[1], item.attributes.length, item.attributes.value[0], self.group_by);
                    area_list_item_widget.on("search_lift_by_area_id", self, self.search_lift_by_area_id);
                    area_list_item_widget.appendTo(self.$el.find("ul.o_baidu_map_lift_distribution_area_list"));
                    self.total_count += item.attributes.length;
                })
                self.$el.find(".tyibs-lift-total-count").html(self.total_count);
            })
        },
        search_lift_by_area_id: function (domain, name, id) {
            var self = this;
            self.trigger("search_lift_by_area_id", domain, name, id);
        },

    });

    var BaiduMapLiftDistributionUseCompanySearchBlockWidget = Widget.extend({
        //左侧使用单位搜索
        "template": "baidu_map_lift_distribution_use_company_search_block",
        init: function (parent, id, name, count) {
            this._super(parent);
            this.id = id;
            this.name = name;
            this.count = count;
        },
        start: function () {
            this.autocomplete();
        },
        autocomplete: function () {
            var self = this;
            self.$el.find(".o_search_input" ).autocomplete({
                source: function (request, response) {
                    var vals = [];
                    var use_company_model = new Model("tyibs.base.lift.use.company");
                    var domain = ['&',['area_id', '=', self.id] , '|', ['phonetic', 'ilike', request.term],
                        '|', ['phonetic_short', 'ilike', request.term], '|', ['address_detail', 'ilike', request.term],
                        '|', ['linkman', 'ilike', request.term], '|',['linkman_tel', 'ilike', request.term],
                        '|',['linkman_phone', 'ilike', request.term],['name', 'ilike', request.term]];
                    use_company_model.query(["name", "lift_count", "ln", "la"]).filter(domain).limit(10).all()
                        .then(function (results) {
                        results.forEach(function (item) {
                            vals.push({id: item.id, ln: item.ln, la: item.la, label: item.name, value: item.name, lift_count : item.lift_count});
                        });
                        response(vals);
                        return;
                    });
                },
                select: function( event, ui ) {
                    var $input_hidden = self.$el.find("input.o_search_input_hidden");
                    $input_hidden.val(ui.item.id + '-' + ui.item.ln + '-' + ui.item.la + '-' + ui.item.value + '-' + ui.item.lift_count);
                    $input_hidden.change();
                },
            });
        },
        events: {
            "change input.o_search_input_hidden": function () {
                var self = this;
                var input_hidden_val = self.$el.find("input.o_search_input_hidden").val().trim().split("-");
                this.trigger("search_lift_by_use_company_id", input_hidden_val[0], input_hidden_val[1], input_hidden_val[2], input_hidden_val[3], input_hidden_val[4]);
            }
        }
    });

    var BaiduMapLiftDistributionLiftSearchBlockWidget = Widget.extend({
        //左侧电梯搜索
        "template": "baidu_map_lift_distribution_use_company_search_block",
        init: function (parent, id, name, count, area_id, area_name) {
            this._super(parent);
            this.id = id*1;
            this.name = name;
            this.count = count;
            this.area_id = area_id;
            this.area_name = area_name;
            this.model = lift_model;
        },
        start: function () {
            this.autocomplete();
        },
        autocomplete: function () {
            var self = this;
            self.$el.find(".o_search_input" ).autocomplete({
                source: function (request, response) {
                    var vals = [];
                    var domain = ['&', ['use_company_id', '=', self.id], '|', ['code', 'ilike', request.term], '|',
                        ['maintenance_company_id.name', 'ilike', request.term], ['use_address', 'ilike', request.term]];
                    self.model.query(["code", "ln", "la", "user_inside_code", "use_address"]).filter(domain).limit(10).all().then(function (results) {
                        results.forEach(function (item) {
                            var label = item.code;
                            if (item.user_inside_code){
                                label += "-" + item.user_inside_code;
                            }
                            if (item.use_address){
                                label += "-" + item.use_address;
                            }
                            vals.push({id: item.id, ln: item.ln, la: item.la, label: label, value: label});
                        });
                        response(vals);
                        return;
                    });
                },
                select: function( event, ui ) {
                    var $input_hidden = self.$el.find("input.o_search_input_hidden");
                    $input_hidden.val(ui.item.id + '-' + ui.item.ln + '-' + ui.item.la);
                    $input_hidden.change();
                },
            });
        },
        events: {
            "change input.o_search_input_hidden": function () {
                var self = this;
                var input_hidden_val = self.$el.find("input.o_search_input_hidden").val().trim().split("-");
                var point = new BMap.Point(input_hidden_val[1], input_hidden_val[2]);
                point.index = input_hidden_val[0];
                this.trigger("orientate_one_lift", [point], point, 15);
                console.log("视角切换至电梯：ID为" + input_hidden_val[0]);
            },
            "click a": function () {
                this.trigger("search_lift_count_group_by_use_company", [['area_id', '=', this.area_id]], this.area_name, this.area_id);
                this.$el.remove();
            },
            'click button.o_baidu_map_lift_distribution_search_btn': function () {
                var search_parm = this.$(".o_search_input").val().trim();
                console.log(search_parm);
                if (search_parm.indexOf("-") != -1){
                    search_parm = search_parm.split("-")[0];
                    this.trigger('search_lift', [['code', '=', search_parm]]);
                }else {
                    this.trigger('search_lift', ['&', ['use_company_id', '=', this.id], '|', ['code', 'ilike', search_parm], '|', ['area_id.name', 'ilike', search_parm], '|',
                        ['use_company_id.name', 'ilike', search_parm], '|',['maintenance_company_id.name', 'ilike', search_parm],
                    ['use_address', 'ilike', search_parm]]);
                }
            },
            'keydown input.o_search_input': function (e) {
                if(e.keyCode == 13){
                    var search_parm = this.$(".o_search_input").val().trim();
                    if (search_parm.indexOf("-") != -1){
                        search_parm = search_parm.split("-")[0];
                        this.trigger('search_lift', [['code', '=', search_parm]])
                    }else {
                        this.trigger('search_lift', ['&', ['use_company_id', '=', this.id], '|', ['code', 'ilike', search_parm], '|', ['area_id.name', 'ilike', search_parm], '|',
                            ['use_company_id.name', 'ilike', search_parm], '|',['maintenance_company_id.name', 'ilike', search_parm],
                        ['use_address', 'ilike', search_parm]]);
                    }
                }
            }
        }
    });

    var BaiduMapLiftDistributionLiftInfoWindow = Widget.extend({
        template: "baidu_map_lift_distribution_lift_info_window",
        init: function (parent, id, use_address, code, lift_status, register_code, next_check_date, use_company, maintenance_company, last_maintenance_date, save_finished_time, service_time) {
            this._super(parent);
            this.lift_id = id;
            this.use_address = use_address;
            this.code = code;
            this.lift_status = lift_status;
            this.register_code = register_code;
            this.next_check_date = next_check_date;
            this.use_company = use_company;
            this.maintenance_company = maintenance_company;
            this.last_maintenance_date = last_maintenance_date;
            this.save_finished_time = save_finished_time;
            this.service_time = service_time;
        },
        start: function () {
            console.log(this.use_company);
        },
        events: {
            "click h4": function () {
                this.do_action({
                    name: this.code,
                    type: 'ir.actions.act_window',
                    res_model: "tyibs.base.lift",
                    res_id: this.lift_id,
                    views: [[false, 'form']],
                    target: 'current',
                    context: {},
                });
            }
        }
    });

    var BaiduMapLiftDistributionBtnBlockWidget = Widget.extend({
        template: "baidu_map_lift_distribution_btn_block",
        init: function (parent) {
            this._super(parent);
        },
        events: {
            "click button.tyibs_map_btn": function (e) {
                this.trigger(e.target.value);
            }
        }
    });

    var BaiduMapLiftDistributionChartsWidget = Widget.extend({
        template: "baidu_map_lift_distribution_charts_block",
        init:function(parent){
            this._super(parent);
        }
    });

    var BaiduMapLiftDistributionStatisticsWidget = Widget.extend({
        template: "baidu_map_lift_distribution_statistics",
        init:function(parent, area_id, area_name){
            this._super(parent);
            // this.total_count = total_count;
            // this.has_not_register = has_not_register;
            this.area_id = area_id;
            // this.area_name = area_name || "全市";
            this.area_name = area_name || "";
            this.total_count = "未知";
            this.has_not_register_count = "未知";
            this.not_check_count = "未知";
            this.recheck_fail_count = "未知";
        },
        start: function () {
            this.get_data();
        },
        get_data: function () {
            var self = this;
            // var lift_model = new Model("tyibs.base.lift");
            // lift_model._context = {'search_from':'lift_distribution'};
            var domain = [];
            var domain_not_register = [['register_status', '=', 'unregistered']];
            var domain_not_check = [['next_check_date', '<', self.format_date_str()]];
            var domain_recheck_fail = [['checkout_result', '=', 're_no']];
            if (self.area_id){
                // lift_model.query(["id", "register_status"]).filter([['area_id', '=', self.area_id]]).all().then(function (result) {
                //     self.total_count = result.length;
                //     self.has_not_register = result.filter(function (item) {
                //         item.register_status == "unregistered";
                //     }).length;
                // })

                domain.push(['area_id', '=', self.area_id]);
                domain_not_register.push(['area_id', '=', self.area_id]);
                domain_not_check.push(['area_id', '=', self.area_id]);
                domain_recheck_fail.push(['area_id', '=', self.area_id]);
            }
            lift_model.query(["id"]).filter(domain).count().then(function (result) {
                self.$(".lift_total_count").text(result);
            });
            lift_model.query(["id"]).filter(domain_not_register).count().then(function (result) {
                self.$(".lift_has_not_register").text(result);
            });
            lift_model.query(["id"]).filter(domain_not_check).count().then(function (result) {
                self.$(".lift_not_check").text(result);
            });
            lift_model.query(["id"]).filter(domain_recheck_fail).count().then(function (result) {
                self.$(".lift_recheck_fail").text(result);
            });
        },
        format_date_str: function () {
            var nowDate = new Date();
            var year = nowDate.getFullYear();
            var month = nowDate.getMonth() + 1 < 10 ? "0" + (nowDate.getMonth() + 1) : nowDate.getMonth() + 1;
            var day = nowDate.getDate() < 10 ? "0" + nowDate.getDate() : nowDate.getDate();
            return year + "-" + month + "-" + day;
        },
        events: {
            "click div.btn_lift_total_count": function (e) {
                if (this.area_id){
                    this.trigger("go_to_lift_list", {
                        "title": this.area_name + "全部电梯",
                        "domain": [['area_id', '=', this.area_id]]
                    });
                }else {
                    this.trigger("go_to_lift_list", {
                        "title": this.area_name + "全部电梯",
                        "domain": []
                    });
                }
            },
            "click div.btn_lift_has_not_register": function (e) {
                if (this.area_id){
                    this.trigger("go_to_lift_list", {
                        "title": this.area_name + "未注册电梯",
                        "domain": [['area_id', '=', this.area_id],['register_status', '=', 'unregistered']]
                    });
                }else {
                    this.trigger("go_to_lift_list",{
                        "title": this.area_name + "未注册电梯",
                        "domain": [['register_status', '=', 'unregistered']]
                    });
                }
            },
            "click div.btn_lift_not_check": function (e) {
                if (this.area_id){
                    this.trigger("go_to_lift_list", {
                        "title": this.area_name + "未经检验使用电梯",
                        "domain": [['area_id', '=', this.area_id],['next_check_date', '<', this.format_date_str()]]
                    });
                }else {
                    this.trigger("go_to_lift_list",{
                        "title": this.area_name + "未经检验使用电梯",
                        "domain": [['next_check_date', '<', this.format_date_str()]]
                    });
                }
            },
            "click div.btn_lift_recheck_fail": function (e) {
                if (this.area_id){
                    this.trigger("go_to_lift_list", {
                        "title": this.area_name + "复检不合格电梯",
                        "domain": [['area_id', '=', this.area_id],['checkout_result', '=', 're_no']]
                    });
                }else {
                    this.trigger("go_to_lift_list",{
                        "title": this.area_name + "复检不合格电梯",
                        "domain": [['checkout_result', '=', 're_no']]
                    });
                }
            }
        }
    });

    core.action_registry.add('lift_base.qs_index', QsIndex);
    core.action_registry.add('lift_base.baidu_map_lift_distribution', BaiduMapLiftDistributionWidget);

    return {
        QsIndex: QsIndex,
        MessageBox: MessageBox,
        BaiduMapLiftDistributionWidget: BaiduMapLiftDistributionWidget,
        BaiduMapLiftDistributionStatisticsWidget: BaiduMapLiftDistributionStatisticsWidget
    }
});